#!/bin/bash
function make_vm_qcow2_main()
{
    get_version
    release_dir=`get_release_dir`
    version_time=${release_dir#/srv/www/htdocs/}
    version_time=${version_time##*/}

    IMG_DIR="../qcow2_image"

    set +e
    if [ ! -d ${IMG_DIR} ]; then
        mkdir -p ${IMG_DIR}
    fi

    if [ -f ks/euleros-ks.cfg ]; then
        rm /var/www/html/ks/euleros-ks.cfg
        cp -f ks/euleros-ks.cfg /var/www/html/ks/euleros-ks.cfg
        chmod -R 755 /var/www/html/ks
    fi

    cp -f vm-install.xml ${IMG_DIR}/
    cp -f grub.cfg /var/lib/tftpboot/
    pushd ${IMG_DIR}

    rm -f vm*.log
    if [ ! -d euleros-iso ];then
        mkdir euleros-iso
    else
        umount euleros-iso
    fi

    if [ -f $DVD_NAME ]; then
        rm $DVD_NAME
    fi

    MOUNT_DIR=`echo $release_dir | cut -d '/' -f 5-9`
    wget -q http://euleros_test:euleros_test@${IP}/$MOUNT_DIR/$SUB_RELEASE_DIR/$DVD_NAME
    mount $DVD_NAME euleros-iso

    if [ ! -f  /var/lib/tftpboot/grubaa64.efi ]; then
        cp euleros-iso/EFI/BOOT/grubaa64.efi /var/lib/tftpboot/
    fi
    cp -f euleros-iso/images/pxeboot/vmlinuz /var/lib/tftpboot/
    cp -f euleros-iso/images/pxeboot/initrd.img /var/lib/tftpboot/
    umount euleros-iso
    chmod -R 755 /var/lib/tftpboot/

    img_name="${ISO_NAME}-${ISO_VERSION}.${ARCH}.qcow2"
    if [ -f $img_name ]; then
        rm $img_name
    fi

    UUID=`cat /proc/sys/kernel/random/uuid`
    VM=vm${UUID}
    sed -i "s/VM_NAME/${VM}/g" vm-install.xml
    sed -i "s:VM_PATH:$PWD:g" vm-install.xml
    DATE=$(date +%Y-%m-%d)
    sed -i "s:LOG_PATH:${PWD}/${VM}_${DATE}_install.log:g" vm-install.xml
    virsh define vm-install.xml
    qemu-img create -f qcow2 $img_name 100G
    DATE=$(date +%Y-%m-%d)
    virsh start $VM
    VM_STATUS="running"
    INSTALL_TIME=0
    while [ "${VM_STATUS}" = "running" ] && [ $INSTALL_TIME -le 1800 ]; do
        sleep 30
        INSTALL_TIME=`expr $INSTALL_TIME + 30`
        VM_STATUS=`virsh domstate $VM`
    done

    grep -nr "Power down" ${VM}_${DATE}_install.log
    if [ $? -eq 0 ]; then
        virsh undefine $VM
        log_info "vm install successful"
    else
        cat ${VM}_${DATE}_install.log
        log_info "vm status is ${VM_STATUS} "
        virsh destroy $VM
        virsh undefine $VM
        rm $img_name
        log_error "install vm failed"
    fi

    set -e
    sha256sum $img_name > ${img_name}${SHA256SUM}
    popd
    log_info "end all"
}

